<template>
  <div class="main">
    <div>
      <el-upload
        :action="upladUrl"
        list-type="picture-card"
        :before-upload="beforeUpload"
        :on-success="handleSuccess"
        :on-remove="handleRemove"
        :file-list="fileList"
        :on-preview="handlePictureCardPreview"
      >
        <i class="el-icon-plus"></i>
        <div slot="tip" class="el-upload__tip">
          1.上传图片支持JPG、GIF、JPEG、PNG格式，单张不超过500kb。
        </div>
      </el-upload>
    </div>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page.sync="listQuery.page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="listQuery.pageSize"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
    <div class="img_content">
      <img />
    </div>
    <el-dialog :visible.sync="dialogVisible">
      <img
        width="100%"
        :src="dialogImageUrl"
        alt=""
      >
    </el-dialog>
  </div>
</template>

<script>
import { getAvatarList, deleteAvatar, addAvatar } from '@/api/commont'

export default {
  name: 'avatarmanage',
  data() {
    return {
      dialogImageUrl: '',
      total: 0,
      dialogVisible: false,
      listQuery: {
        page: 0,
        pageSize: 10
      },
      fileList: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    async getList() {
      try {
        const { data } = await getAvatarList(this.listQuery)
        this.fileList = []
        this.fileList = data.rows
        this.total = Number(data.total)
      } catch (error) {
        console.log(error)
      }
    },
    async handleSuccess(res) {
      try {
        const data = await addAvatar({ urls: [res.filePath] })
        if (data.message === 'SUCCESS') {
          this.$message.success('上传成功')
          this.getList()
        }
      } catch (error) {
        console.log(error)
      }
    },
    async handleRemove(file) {
      try {
        const data = await deleteAvatar({ id: file.id })
        if (data.message === 'SUCCESS') {
          this.$message.success('删除成功')
          this.getList()
        }
      } catch (error) {
        console.log(error)
        this.$message.error('操作失败')
      }
      console.log(file, fileList)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 切换分页
    handleCurrentChange(page) {
      this.listQuery.page = page
      this.getList()
    },
    //切换每页条数
    handleSizeChange(value) {
      this.listQuery.pageSize = value
      this.getList()
    }
  }
}
</script>

<style lang="scss" scoped>
/deep/ .el-upload-list__item {
  transition: none;
}
</style>